package com.laikan.library.httpvolley.engine;

import android.content.Context;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.RequestQueue.RequestFilter;
import com.android.volley.toolbox.Volley;
import com.laikan.library.httpvolley.helper.RequestListener;

/**
 * 全局的发起网络请求的类
 *
 * @author anrun
 */
public class HttpApiRequestEngine {

    private RequestQueue requestQueue;
    private static HttpApiRequestEngine instance;

    public static HttpApiRequestEngine getInstance() {

        if(instance == null) {
            synchronized(HttpApiRequestEngine.class) {
                instance = new HttpApiRequestEngine();
            }
        }
        return instance;
    }

    // 在程序启动的时候必须进行初始化
    public void init(Context context) {

        requestQueue = Volley.newRequestQueue(context);
    }

    public void httpGetRequest(Requester requester, RequestListener requestListener) {
        BaseHttpRequester.newInstance(requestQueue, requestListener).doCommonGetRequest(requester);
    }

    public void httpPostRequest(Requester requester, RequestListener requestListener) {
        BaseHttpRequester.newInstance(requestQueue, requestListener).doCommonPostRequest(requester);
    }

    public void cancelAllRequestByTag(Object tag) {

        requestQueue.cancelAll(tag);
    }

    public void cancelAllRequest() {

        RequestFilter filter = new RequestFilter() {

            @Override
            public boolean apply(Request<?> arg0) {

                // TODO Auto-generated method stub
                return false;
            }
        };
        requestQueue.cancelAll(filter);
    }
}
